import { LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { Form, Menu, Spin, Modal, Input, message } from 'antd';
import { useRef, useState } from 'react';
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min.js';
import { connect } from 'dva';
import { useModel } from 'umi';
import request from '@/utils/request';
import { modalFormItemLayout, modalProps } from './layout.config';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';

const key =
  'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJZrad51I1vPRoAtzHop3bnMuKS1Z614m8obzURJIGuecqlTXpQlN7i/hXxC5IBuJ/t2PndNvF5QN0VldqFhtIsCAwEAAQ==';
const encryptor = new JSEncrypt();

encryptor.setPublicKey(key);
function AvatarDropdown(props) {
  const formRef = useRef();
  const [showModifyDrawer, setShowModifyDrawer] = useState(false);
  const { setInitialState } = useModel('@@initialState');

  const logout = () => {
    const { dispatch } = props;
    dispatch({
      type: 'userLogin/logout',
    });
    setInitialState({});
  };

  // 处理取消和确认操作
  const handleOperate = () => {
    setShowModifyDrawer(prev => !prev);
  };

  const onMenuClick = event => {
    const { key } = event;
    if (key === 'logout') {
      logout();
    } else if (key === 'settings') {
      handleOperate();
    }
  };

  const formatData = params => {
    const formData = new FormData();
    Object.keys(params).map(key => formData.append(key, params[key]));
    return formData;
  };

  const checkOldPwd = value => {
    if (!value) {
      return;
    }
    const { username } = props.currentUser;
    const jsencrypt = new JSEncrypt();
    jsencrypt.setPublicKey(key);
    const password = jsencrypt.encrypt(value);
    const params = {
      username,
      password,
    };
    request('/user/password/check', {
      method: 'POST',
      params,
    }).then(
      res => {
        if (!res?.success) {
          message.warn(res.errorMsg || res?.message || '网络异常，请重试');
        }

        if (!res?.data) {
          formRef.current.setFields([
            {
              name: 'oldPassword',
              value,
              errors: ['输入的密码与旧密码不一致'],
            },
          ]);
        }

        return res?.data;
      },
      err => {
        console.log(err);
      },
    );
  };

  const handleSubmit = () => {
    formRef.current
      .validateFields()
      .then(async values => {
        const oldPwdOk = await checkOldPwd(values.oldPassword);
        if (oldPwdOk) {
          const { username } = props.currentUser;
          const jsencrypt = new JSEncrypt();
          jsencrypt.setPublicKey(key);
          const password = jsencrypt.encrypt(values.newPassword);
          const oldPassword = jsencrypt.encrypt(values.oldPassword);
          const params = {
            password,
            originPassword: oldPassword,
            username,
          };
          request('/user/password', {
            method: 'post',
            data: formatData(params),
          }).then(res => {
            if (res.success) {
              message.success('修改密码成功,请重新登录');
              setShowModifyDrawer(false);
              logout();
            } else {
              message.warn(res?.message || res?.errorMsg || '修改密码失败，请重试');
            }
          });
        }
      })
      .catch(() => {});
  };

  const compareToFirstPassword = (rule, value, callback) => {
    if (value && value !== formRef.current.getFieldValue('newPassword')) {
      callback('两次输入密码不一致!');
    } else {
      callback();
    }
  };

  const validateToNextPassword = (rule, value, callback) => {
    if (value) {
      formRef.current.validateFields(['confirmPassword'], { force: true });
    }
    callback();
  };

  const menuHeaderDropdown = () => (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="settings">
        <SettingOutlined />
        <span>修改密码</span>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined />
        <span>退出登录</span>
      </Menu.Item>
    </Menu>
  );
  const { currentUser = {} } = props;

  return currentUser && currentUser.username ? (
    <div>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <span className={styles.name}>{currentUser.username}</span>
        </span>
      </HeaderDropdown>
      {showModifyDrawer && (
        <Modal
          title="修改密码"
          visible
          onClose={handleOperate}
          onOk={handleSubmit}
          onCancel={handleOperate}
          {...modalProps}
        >
          <Form {...modalFormItemLayout} ref={formRef}>
            <Form.Item
              label="旧密码"
              name="oldPassword"
              rules={[
                {
                  required: true,
                  message: '请输入旧密码',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="新密码"
              hasFeedback
              name="newPassword"
              rules={[
                {
                  required: true,
                  message: '请输入新密码!',
                },
                {
                  validator: validateToNextPassword,
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="确认密码"
              hasFeedback
              name="confirmPassword"
              rules={[
                {
                  required: true,
                  message: '请再次输入您的新密码!',
                },
                {
                  validator: compareToFirstPassword,
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
          </Form>
        </Modal>
      )}
    </div>
  ) : (
    <Spin
      size="small"
      style={{
        marginLeft: 8,
        marginRight: 8,
      }}
    />
  );
}
export default connect(({ userLogin }) => ({
  currentUser: userLogin.currentUser,
}))(AvatarDropdown);
